package com.lanvideo.dao;

import com.lanvideo.entity.ExamAnswer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.ArrayList;

/**
 * 考试答题记录数据访问层
 */
@Repository
public class ExamAnswerDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 保存学生答题记录
     */
    public int saveAnswer(ExamAnswer answer) {
        String sql = "INSERT INTO exam_answer (exam_id, student_id, question_id, student_answer, correct_answer, is_correct, answer_time) " +
                "VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)";
        return jdbcTemplate.update(sql, answer.getExamId(), answer.getStudentId(), answer.getQuestionId(),
                answer.getStudentAnswer(), answer.getCorrectAnswer(), answer.getIsCorrect());
    }

    /**
     * 批量保存学生答题记录
     */
    public int[] batchSaveAnswers(List<ExamAnswer> answers) {
        String sql = "INSERT INTO exam_answer (exam_id, student_id, question_id, student_answer, correct_answer, is_correct, answer_time) " +
                "VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)";
        
        List<Object[]> batchArgs = new ArrayList<>();
        for (ExamAnswer answer : answers) {
            batchArgs.add(new Object[]{
                answer.getExamId(),
                answer.getStudentId(),
                answer.getQuestionId(),
                answer.getStudentAnswer(),
                answer.getCorrectAnswer(),
                answer.getIsCorrect()
            });
        }
        
        return jdbcTemplate.batchUpdate(sql, batchArgs);
    }

    /**
     * 获取学生的考试答题记录
     */
    public List<ExamAnswer> getStudentExamAnswers(Integer examId, Integer studentId) {
        String sql = "SELECT ea.*, q.content as question_content, q.option_a, q.option_b, q.option_c, q.option_d, q.type as question_type " +
                "FROM exam_answer ea " +
                "LEFT JOIN question_bank q ON ea.question_id = q.id " +
                "WHERE ea.exam_id = ? AND ea.student_id = ? " +
                "ORDER BY ea.question_id";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<ExamAnswer>() {
            @Override
            public ExamAnswer mapRow(java.sql.ResultSet rs, int rowNum) throws java.sql.SQLException {
                ExamAnswer answer = new ExamAnswer();
                answer.setId(rs.getInt("id"));
                answer.setExamId(rs.getInt("exam_id"));
                answer.setStudentId(rs.getInt("student_id"));
                answer.setQuestionId(rs.getInt("question_id"));
                answer.setStudentAnswer(rs.getString("student_answer"));
                answer.setCorrectAnswer(rs.getString("correct_answer"));
                answer.setIsCorrect(rs.getBoolean("is_correct"));
                answer.setAnswerTime(rs.getTimestamp("answer_time") != null ? 
                    rs.getTimestamp("answer_time").toLocalDateTime() : null);
                
                // 设置题目相关字段
                answer.setQuestionContent(rs.getString("question_content"));
                answer.setOptionA(rs.getString("option_a"));
                answer.setOptionB(rs.getString("option_b"));
                answer.setOptionC(rs.getString("option_c"));
                answer.setOptionD(rs.getString("option_d"));
                answer.setQuestionType(rs.getInt("question_type"));
                
                return answer;
            }
        }, examId, studentId);
    }

    /**
     * 获取考试的所有答题记录
     */
    public List<ExamAnswer> getExamAnswers(Integer examId) {
        String sql = "SELECT ea.*, q.content as question_content, q.option_a, q.option_b, q.option_c, q.option_d, q.type as question_type, " +
                "u.name as student_name " +
                "FROM exam_answer ea " +
                "LEFT JOIN question_bank q ON ea.question_id = q.id " +
                "LEFT JOIN user u ON ea.student_id = u.id " +
                "WHERE ea.exam_id = ? " +
                "ORDER BY ea.student_id, ea.question_id";
        
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<ExamAnswer>() {
            @Override
            public ExamAnswer mapRow(java.sql.ResultSet rs, int rowNum) throws java.sql.SQLException {
                ExamAnswer answer = new ExamAnswer();
                answer.setId(rs.getInt("id"));
                answer.setExamId(rs.getInt("exam_id"));
                answer.setStudentId(rs.getInt("student_id"));
                answer.setQuestionId(rs.getInt("question_id"));
                answer.setStudentAnswer(rs.getString("student_answer"));
                answer.setCorrectAnswer(rs.getString("correct_answer"));
                answer.setIsCorrect(rs.getBoolean("is_correct"));
                answer.setAnswerTime(rs.getTimestamp("answer_time") != null ? 
                    rs.getTimestamp("answer_time").toLocalDateTime() : null);
                
                // 设置题目相关字段
                answer.setQuestionContent(rs.getString("question_content"));
                answer.setOptionA(rs.getString("option_a"));
                answer.setOptionB(rs.getString("option_b"));
                answer.setOptionC(rs.getString("option_c"));
                answer.setOptionD(rs.getString("option_d"));
                answer.setQuestionType(rs.getInt("question_type"));
                
                return answer;
            }
        }, examId);
    }

    /**
     * 获取特定题目的所有学生答案
     */
    public List<ExamAnswer> getQuestionAnswers(Integer examId, Integer questionId) {
        String sql = "SELECT ea.*, u.name as student_name " +
                "FROM exam_answer ea " +
                "LEFT JOIN user u ON ea.student_id = u.id " +
                "WHERE ea.exam_id = ? AND ea.question_id = ? " +
                "ORDER BY ea.student_id";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(ExamAnswer.class), examId, questionId);
    }

    /**
     * 删除学生的考试答题记录
     */
    public int deleteStudentAnswers(Integer examId, Integer studentId) {
        String sql = "DELETE FROM exam_answer WHERE exam_id = ? AND student_id = ?";
        return jdbcTemplate.update(sql, examId, studentId);
    }

    /**
     * 获取学生的答题统计
     */
    public ExamAnswer getStudentAnswerStats(Integer examId, Integer studentId) {
        String sql = "SELECT " +
                "COUNT(*) as total_questions, " +
                "SUM(CASE WHEN is_correct = 1 THEN 1 ELSE 0 END) as correct_count " +
                "FROM exam_answer " +
                "WHERE exam_id = ? AND student_id = ?";
        
        List<ExamAnswer> results = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(ExamAnswer.class), examId, studentId);
        return results.isEmpty() ? null : results.get(0);
    }
}
